/**
* @author StevenDong/kingdeezhao@gmail.com
* @date 2020/12/14 9:30 上午
* @Description:
* @params:
*/

export default class Messager {
    constructor (win, targetOrigin) {
        this.win = win;
        this.targetOrigin = targetOrigin;
        this.actions = {};
        window.addEventListener('message', this.handleMessageListener, false);
    }
    handleMessageListener = (event) => {
        if (event.origin !== this.targetOrigin) {
        }
        if (!event.data || !event.data.type) {

        }
        const { type } = event.data;
        if (!this.actions[type]) {
            console.warn(`${type}: missing listener`);
            return;
        }
        this.actions[type](event.data.value);
    };
    on = (type, cb) => {
        this.actions[type] = cb;
        return this;
    };

    emit = (type, value) => {
        this.win.postMessage({
            type, value
        }, this.targetOrigin);
        return this;
    };

    destroy () {
        window.removeEventListener('message', this.handleMessageListener);
    }
}
